jQuery(document).ready(function($) {
   $('#selectcity_btn,#location,.thirdparty_location').click(function(){
       var target = $(this);
       $.ajax({
           type: "GET",
           url: OC.filePath('jobposition', 'ajax', 'getpositionarea.php'),
           data: {
              ids:$('#location_ids').val(),
              source:target.data('source'),
              state:$("#jobpos_state").val(),
              id_state:$("#jobpos_id_state").val(),
              id_city:$("#jobpos_id_city").val(),
              source_id_city:$("#"+target.data('source')+"_id_city").val()
              },
           dataType: 'html',
           success: function(result) {
              $("#selectcity_dialog .modal-body").html(result);
              var scrolltop = $(window).scrollTop();
              $("#selectcity_dialog").css({top:scrolltop+75}).modal('show');
           }
        });
   });
   
   $('#job_position_form').on("click", ".showposcateg", function() {
      var target = $(this);
       $.ajax({
           type: "GET",
           url: OC.filePath('jobposition', 'ajax', 'getpositioncateg.php'),
           data: {source:$(this).data('source'), position_type:$(this).data('type'),position_id:$('#'+$(this).data('type')).val()},
           dataType: 'html',
           beforeSend: function(xhr, settings) {
              showLoading(target, settings, null, {button:true});
           },
           success: function(result) {
              $("#selectwork_dialog .modal-body").html(result);
              // modal changed from fix to absolute, so the dialog is only on top part of view window -- need to be adjusted to be centered 
              var scrolltop = $(window).scrollTop();
              $("#selectwork_dialog").css({top:scrolltop+75}).modal('show');
           }
        });
   });

   $('#postjobconfirm').click(function(){
      tinymce.triggerSave();
      $('#job_position_form').submit();
   });
   
   $('#selectwork_dialog').on('click','.removeselected',function(){
      var pos_type=$('#select_pos_type').val();
      $('.selectwork_listdialog,.selectwork_table').find('a.selected').removeClass('selected');
      $('.selectwork_listdialog').hide();
      $('#'+pos_type).val('');
      $('#'+pos_type+'_text').val('');
   })
   
   $.validator.addMethod(
      "agerange",
      function(value, element, param) {
         var startagefield = $(element).hasClass("startage") ? $(element) : $(element).prevAll('.startage'),
             endagefield = $(element).hasClass("endage") ? $(element) : $(element).nextAll('.endage'),
             startvalue = $.trim(startagefield.val()), 
             endvalue = $.trim(endagefield.val()),
             valid = true; 

         if(startvalue.length <= 0 && endvalue.length <= 0)
            valid = true;
         else {
            // always validate start age 
            if(!/^\d+$/.test(startvalue))
               valid = false; 
            if(startvalue < 18)
               valid = false; 

            // don't check endage field if checking start age field and it's valid 
            if($(element).hasClass("startage") && valid)
               return true; 

            // don't check endage field if start field is wrong 
            if($(element).hasClass("endage") && !valid)
               return true; 

            if(!/^\d+$/.test(endvalue))
               valid = false; 
            if(endvalue > 65)
               valid = false; 
            
            if(parseInt(startvalue) > parseInt(endvalue))
               valid = false; 
         }
         return this.optional(element) || valid;
      },
      function (param, element) { 
         var startagefield = $(element).hasClass("startage") ? $(element) : $(element).prevAll('.startage'),
             endagefield = $(element).hasClass("endage") ? $(element) : $(element).nextAll('.endage'),
             startvalue = $.trim(startagefield.val()), 
             endvalue = $.trim(endagefield.val());

         if(!/^\d+$/.test(startvalue) || startvalue < 18)
             return "请输入初始年龄最小为18的整数"; 

         if(!/^\d+$/.test(endvalue) || endvalue > 65)
             return "请输入年龄最大为65的整数"; 
            
         if(parseInt(startvalue) > parseInt(endvalue))
             return "请输入合法的年龄要求范围";

         // should not reach here but default message 
         return "请输入合法的数字"
      }
   );

   $.validator.addMethod(
      "salaryrange",
      function(value, element, param) {
         var startsalaryfield = $(element).hasClass("startsalary") ? $(element) : $(element).prevAll('.startsalary'),
             endsalaryfield = $(element).hasClass("endsalary") ? $(element) : $(element).nextAll('.endsalary'),
             startvalue = $.trim(startsalaryfield.val()), 
             endvalue = $.trim(endsalaryfield.val()),
             valid = true; 

         if(startvalue.length <= 0 && endvalue.length <= 0)
            valid = true;
         else {
            // always validate start age 
            if(!/^\d+$/.test(startvalue))
               valid = false; 
            if(startvalue < 1 || startvalue > 100)
               valid = false; 

            // don't check startsalary field if checking start salary field and it's valid 
            if($(element).hasClass("startsalary") && valid)
               return true; 

            // don't check endsalary field if start field is wrong 
            if($(element).hasClass("endsalary") && !valid)
               return true; 

            if(!/^\d+$/.test(endvalue))
               valid = false; 
            if(endvalue < 1 || endvalue > 100)
               valid = false; 
            if(parseInt(startvalue) >= parseInt(endvalue))
               valid = false;
            if(parseInt(startvalue) < parseInt(endvalue)/2)
               valid = false;

            
         }
         return this.optional(element) || valid;
      },
      function (param, element) { 
         var startsalaryfield = $(element).hasClass("startsalary") ? $(element) : $(element).prevAll('.startsalary'),
             endsalaryfield = $(element).hasClass("endsalary") ? $(element) : $(element).nextAll('.endsalary'),
             startvalue = $.trim(startsalaryfield.val()), 
             endvalue = $.trim(endsalaryfield.val());

         if(!/^\d+$/.test(startvalue) || startvalue < 1 || startvalue > 100)
             return "请输入有效的月薪范围，1k-100k"; 

         if(!/^\d+$/.test(endvalue) || endvalue < 1 || endvalue > 100)
             return "请输入有效的月薪范围，1k-100k"; 

         if(parseInt(startvalue) >= parseInt(endvalue))
             return "最高月薪需大于最低月薪";

         if(parseInt(startvalue) < parseInt(endvalue)/2)
             return "最高月薪不能大于最低月薪的2倍"; 
            
         

         // should not reach here but default message 
         return "请输入合法的数字"
      }
   );

   $.validator.addMethod(
      "lagou_positionadvantage",
      function(value, element, param) {
         var positionadvantage = $(element).hasClass("lagou_positionadvantage") ? $(element) : $(element).prevAll('.lagou_positionadvantage'),
             positionadvantage = $.trim(positionadvantage.val()),
             valid = true; 
         if(positionadvantage.length <= 0)
            valid = false;
         if(positionadvantage.length > 20){
            valid = false; 
         }
         return this.optional(element) || valid;
      },
      function (param, element) { 
         var positionadvantage = $(element).hasClass("lagou_positionadvantage") ? $(element) : $(element).prevAll('.lagou_positionadvantage'),
             positionadvantage = $.trim(positionadvantage.val());

         if(positionadvantage.length>20){
            return "职位诱惑限20字内"; 
         }

         // should not reach here but default message 
         return "请输职位诱惑"
      }
   );

   $.validator.addClassRules("agerange", {agerange: true}); 
   $.validator.addClassRules("salaryrange", {salaryrange: true}); 
   $.validator.addClassRules("lagou_positionadvantage", {lagou_positionadvantage: true}); 
   
   var validator = {
      rules: {
         long_desc: {
            required: true,
            rangeChars: [10,1000]
         },
      },
      messages: {
         long_desc: {
            rangeChars: '请在10-1000个字符之内详细说明您的职位'
         },
      },
      submitHandler: function(form) {
         $(form).ajaxSubmit({
           dataType: "json",
           beforeSubmit: function(data, form, options) {
              $('.systemerror', form).hide().html('');
               if(!showLoading(form))
                  return false;
            },
            success: function(data) {
              try {
                 if(data.error) { 
                    $('.systemerror', form).show().html(data.error);
                 }else if(data.success){
                    location.href = data.redirect; // Don't use reload here to filter the sconfirm in the url
                 }
              } catch(e) {
                 return false;
              }
            }
        });
      }
   };
   $("#job_position_form").validate(validator);
   
   $('#selectcitycancel').click(function(){
       var source =$("#dialog_source").val();
       if(source){
          $(".dialogp_content .allcitylist").find('a.cur_a').removeClass('cur_a');
       }else{
          $('.other_area_select').hide();
          var city = $('#areatagsbox input[type=hidden]');
          city.each(function(){
              $("#areatagsbox").tagit('removeTagByName', $(this).val());
          });
       }    
   });
   //area dialog confirm btn click
   $('#selectcityconfirm').click(function(){
      var source =$("#dialog_source").val();
      if(source && $("#"+source+"_city_text") && $("#"+source+"_id_city")){
         var cur_select = $(".dialogp_content .allcitylist a.cur_a");
         if(cur_select.length>0){
            $("#"+source+"_city_text").val(cur_select.data('city')).focus();
            $("#"+source+"_id_city").val(cur_select.data('id_city'));
         }
         $("#selectcity_dialog").modal('hide'); 
      }else{
         var title = '' ,cid = '';
         $("#areatagsbox li.tagit-choice").each(function() {
             var cityid = $(this).find("input").val();
             var citytitle = $(this).find(".tagit-label").text();
             cid = (cid == '') ? cityid.toString() : cid + ',' + cityid.toString();
             title = (title == '') ? citytitle.toString() : title + ',' + citytitle.toString();
         });
         $("#location_ids").val(cid);
         $("#location").val(title).focus();
         $("#selectcity_dialog").modal('hide'); 
      }     
   });

   $('.purposlistbox').on("click","#selectworkconfirm",function(){
      var target = $(this);
      var work_id = $('#select_work_id').val();
      var work_text = $('#select_work_text').val();
      var source = $('#select_source').val();
      var select_pos_type = $('#select_pos_type').val();
      var sources_string = $('#job_position_form').data('sources');
      var sources = sources_string.split(',');

      if (work_id.length > 0 && work_text.length > 0) {
         $('#'+select_pos_type).val(work_id);
         $('#'+select_pos_type+'_text').val(work_text).focus();
      } else {
         $('#'+select_pos_type+'_text').focus();
      }

      if (source == 'pipapai' && work_id.length > 0 && sources_string.length > 0) {
         $.ajax({
            type: "GET",
            url: OC.filePath('jobposition', 'ajax', 'getposdetail.php'),
            data: {pos_id: work_id, sources: sources_string},
            dataType: 'json',
            beforeSend: function(xhr, settings) {
               showLoading(target, settings, null, {button:true});
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               if(result.status == 'success') {
                  var pdata = result.data; // Position data
                  for (var i = sources.length - 1; i >= 0; i--) {
                     if(sources[i]=='51job') continue;
                     if (pdata[sources[i]+'_id'] && pdata[sources[i]+'_id'].length > 0) {
                        $('#'+sources[i]+'_'+select_pos_type).val(pdata[sources[i]+'_id']);
                        $('#'+sources[i]+'_'+select_pos_type+'_text').val(pdata[sources[i]+'_text']);
                        $('#'+sources[i]+'_'+select_pos_type+'_html').html(pdata[sources[i]+'_text']);
                     }
                  }
               }
            }
         });
      }

      $("#selectwork_dialog").modal('hide');
      $('#select_work_id').val('');
      $('#select_work_text').val('');
   });
   
   $("#postjobcancel").click(function(){
      $("#jobdetails #job_position_info , #jobdetails #edit_job_position , #jobdetails #sync_job_position").show();
      $("#jobdetails #job_position_edit").hide();
   });
   
   $("#postjobback").click(function(){
      location.href = jobposindex_url;
   });
   
   $(".hr_innerwrap").on("click","i.close_ibtn",function(){
      $(this).parent().hide().removeData('position');
   });

   $('#job_position_form').on("click", ".poseditbtn", function() {
      var source = $(this).data("source");
      var seq = $(this).data("seq");
      $('#'+source+'_pos'+seq+'_show').hide();
      $('#'+source+'_pos'+seq+'_edit').show();
   });
   
   $('#job_position_form').on("click", ".cityeditbtn", function() {
      var source = $(this).data("source");
      $('#'+source+'_city_show').hide();
      $('#'+source+'_city_edit').show();
   });

   $(".sync_ctl input").on("click", function() {
      var type = $("#job_position_edit").data("type")
      var source = $(this).parent().data("source");
      if (source == "51job") {
         return;
      }
      var sources_string = $('#job_position_form').data('sources');
      var sources = sources_string.split(',');
      var jobpos_id_city =$("#jobpos_id_city").val();
      var checked = $('#syncs_'+source).find("input:checked");
      //Need check the checked box if have position_type,id_city
      var jobid =$("input[name='job_id']").val();
      if(checked.length && source !="51job"){
         if(jobid && source.length>0){
            $.ajax({
               type: "GET",
               url: OC.filePath('jobposition', 'ajax', 'getposdetail.php'),
               data: {job_id: jobid, sources: source},
               dataType: 'json',
               success:function(result){
                  if(!$.isPlainObject(result)) {
                     result = $.parseJSON(result);
                  }                
                  var pdata = result.data;
                  if($('#'+source+'_id_pos_type').val().length <= 0 && pdata[source+'_id1']>0){                       
                     $('#'+source+'_pos1_show').show();
                     $('#'+source+'_id_pos_type').val(pdata[source+'_id1']);
                     $("#"+source+"_id_pos_type_html").html(pdata[source+'_text1']);
                     $("#"+source+"_id_pos_type_text").val(pdata[source+'_text1']);
                     $('#'+source+'_pos1_edit').hide();        
                  }
                  if(typeof($('#'+source+'_id_pos_type2').val())!='undefined' && $('#'+source+'_id_pos_type2').val().length <= 0 && pdata[source+'_id2']>0){
                     $('#'+source+'_pos2_show').show();
                     $('#'+source+'_id_pos_type2').val(pdata[source+'_id2']);
                     $("#"+source+"_id_pos_type2_html").html(pdata[source+'_text2']);
                     $("#"+source+"_id_pos_type2_text").val(pdata[source+'_text2']);
                     $('#'+source+'_pos2_edit').hide();        
                  }
                  if(pdata.id_city<=0 && pdata[source+'_id_city']>0 && $('#'+source+'_id_city').val().length <= 0){
                     $('#'+source+'_city_show').show();
                     $('#'+source+'_id_city').val(pdata[source+'_id_city']);
                     $("#"+source+"_id_city_html").html(pdata[source+'_city']);
                     $('#'+source+'_city_text').val(pdata[source+'_city']);
                     $('#'+source+'_city_edit').hide();                        
                  }
                  if(source == 'lagou'){
                     $('#'+source+'_salary_div').show();
                     $('#'+source+'_salaryrange').prop('disabled', false);
                     $('#'+source+'_advantage_div').show();
                     $('#'+source+'_positionadvantage').prop('disabled', false);
                     $('#'+source+'_jobtype_div').show();
                     $('#'+source+'_employment_type').prop('disabled', false);
                     $('#'+source+'_address_div').show();
                     $('#'+source+'_positionaddress').prop('disabled', false);
                  }else if(pdata['id_city']<=0 && pdata[sources[i]+'_id_city'] && pdata[sources[i]+'_id_city']<=0){
                     $('#'+source+'_jobtype_div').hide();
                     $('#'+source+'_employment_type').prop('disabled', true);
                     $('#'+source+'_advantage_div').hide();
                     $('#'+source+'_positionadvantage').prop('disabled', true);
                     $('#'+source+'_salary_div').hide();
                     $('#'+source+'_salaryrange').prop('disabled', true);
                     $('#'+source+'_address_div').hide();
                     $('#'+source+'_positionaddress').prop('disabled', true);
                  }
               }
            })
         }
         
         // Add new source to sources
         var sindex = sources.indexOf(source);
         if (sindex === -1 ) {
            sources.push(source);
            sources_string = sources.join(",");
            $('#job_position_form').data('sources', sources_string);
         }
         if ($('#'+source+'_pos_div1').is(':hidden')) {
            if($('#'+source+'_id_pos_type').val().length <= 0){
               $('#'+source+'_pos1_show').hide();
               $('#'+source+'_id_pos_type, #'+source+'_id_pos_type_text').prop('disabled', false);
               $('#'+source+'_pos1_edit, #'+source+'_pos_div1').show();
            }else{
               $('#'+source+'_pos_div1').show();
            }            
         }
         if ($('#'+source+'_pos_div2').is(':hidden')) {
            if($('#'+source+'_id_pos_type2').val().length <= 0){
               $('#'+source+'_pos2_show').hide();
               $('#'+source+'_id_pos_type2, #'+source+'_id_pos_type2_text').prop('disabled', false);
               $('#'+source+'_pos2_edit, #'+source+'_pos_div2').show();
            }else{
               $('#'+source+'_pos_div2').show();
            }            
         }

         if ($('#'+source+'_salary_div').is(':hidden')) {
            $('#'+source+'_salary_div').show();
            $('#'+source+'_salaryrange').prop('disabled', false);
         }

         if ($('#'+source+'_advantage_div').is(':hidden')) {
            $('#'+source+'_advantage_div').show();
            $('#'+source+'_positionadvantage').prop('disabled', false);
         }

         if ($('#'+source+'_address_div').is(':hidden')) {
            $('#'+source+'_address_div').show();
            $('#'+source+'_positionaddress').prop('disabled', false);
         }
         
         if( jobpos_id_city<=0 && $('#'+source+'_city_div') && $('#'+source+'_city_div').is(':hidden')){
            if($('#'+source+'_id_city').val().length <= 0){
               $('#'+source+'__city_show').hide();
               $('#'+source+'_city, #'+source+'_city_text').prop('disabled', false);
               $('#'+source+'_city_div,#'+source+'_city_edit').show();
            }else{
               $('#'+source+'_city_div').show();
            }
            
         }
      } else {
         // Delete old source from sources
         var sindex = sources.indexOf(source);
         sources.splice(sindex, 1);
         sources_string = sources.join(",");
         if (!$('#'+source+'_salary_div').is(':hidden')) {
            $('#'+source+'_salary_div').hide();
            $('#'+source+'_salaryrange').prop('disabled', true);
         }
         
         if (!$('#'+source+'_advantage_div').is(':hidden')) {
            $('#'+source+'_advantage_div').hide();
            $('#'+source+'_positionadvantage').prop('disabled', true);
         }

         if (!$('#'+source+'_address_div').is(':hidden')) {
            $('#'+source+'_address_div').hide();
            $('#'+source+'_positionaddress').prop('disabled', true);
         }
         $('#job_position_form').data('sources', sources_string);
         if ($('#'+source+'_id_pos_type') && $('#'+source+'_id_pos_type').val().length <= 0) {
            $('#'+source+'_id_pos_type, #'+source+'_id_pos_type_text').prop('disabled', true);
            $('#'+source+'_pos_div1').hide();
         }else{
            $('#'+source+'_pos_div1').hide();
         }
         if (typeof($('#'+source+'_id_pos_type2').val())!='undefined' && $('#'+source+'_id_pos_type2') && $('#'+source+'_id_pos_type2').val().length <= 0) {
            $('#'+source+'_id_pos_type2, #'+source+'_id_pos_type2_text').prop('disabled', true);
            $('#'+source+'_pos_div2').hide();
         }else{
            $('#'+source+'_pos_div2').hide();
         }
         if (type == "edit" && source == "zhilian") {
            if ($('#'+source+'_id_city') && $('#'+source+'_id_city').val().length <= 0) {
               $('#'+source+'_city').prop('disabled', true);
               $('#'+source+'_city_div,#'+source+'_city_edit').hide();
            }else{
               $('#'+source+'_city_div').hide();
            }
         }

         
      }
   });

});
